package cn.yusei.teamTribe.controller.post;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.yusei.teamTribe.constant.PostTagType;
import cn.yusei.teamTribe.constant.ResponseCode;
import cn.yusei.teamTribe.service.post.PostTagService;
import cn.yusei.teamTribe.util.ResponseUtil;

@Controller
public class PostTagController {

	@Autowired
	private PostTagService postTagService;
	
	@RequestMapping(value="/postTag/add")
	public void add(@RequestAttribute int id, @RequestParam int postId, @RequestParam int tagId, PrintWriter out)
	{
		if(postId <= 0 || !PostTagType.isPostTagType(tagId))
		{
			ResponseUtil.responseCode(out, ResponseCode.PARAM_ILLEGAL);
			return;
		}
		int code = 0;
		try
		{
			code = postTagService.add(id, postId, tagId);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			ResponseUtil.responseCode(out, ResponseCode.SERVER_ERROR);
			return;
		}
		ResponseUtil.responseCode(out, code);
	}
	
	@RequestMapping(value="/postTag/delete")
	public void delete(@RequestAttribute int id, @RequestParam int postId, @RequestParam int tagId, PrintWriter out)
	{
		if(postId <= 0 || !PostTagType.isPostTagType(tagId))
		{
			ResponseUtil.responseCode(out, ResponseCode.PARAM_ILLEGAL);
			return;
		}
		int code = 0;
		try
		{
			code = postTagService.delete(id, postId, tagId);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			ResponseUtil.responseCode(out, ResponseCode.SERVER_ERROR);
			return;
		}
		ResponseUtil.responseCode(out, code);
	}
	
	@RequestMapping(value="/postTag/get")
	public void get(@RequestParam int postId, PrintWriter out)
	{
		if(postId <= 0)
		{
			ResponseUtil.responseCode(out, ResponseCode.PARAM_ILLEGAL);
			return;
		}
		int[] tags = null;
		try
		{
			tags = postTagService.get(postId);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			ResponseUtil.responseCode(out, ResponseCode.SERVER_ERROR);
			return;
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("tags", tags);
		ResponseUtil.response(out, ResponseCode.REQUEST_SUCCESSED, param);
	}
}
